package com.lelv.framework.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.lelv.framework.plugin.Page;

public class BaseDao<T> extends HibernateDaoSupport implements IBaseDao{

	private Class<T> entityClass;

	/*
	 * 在构造方法里通过反射获取当前DAO实体类型
	 */
	public BaseDao(){
		this.entityClass = null;
		Class c = getClass();
		Type t = c.getGenericSuperclass();
		if(t instanceof ParameterizedType){
			Type[] p = ((ParameterizedType) t).getActualTypeArguments();
			this.entityClass = (Class<T>)p[0];
		}
	}

	@Override
	public T get(Long id) {
		// TODO Auto-generated method stub
		return (T)this.getHibernateTemplate().get(entityClass, id);
	}

	@Override
	public void save(Object entity) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().save(entity);
	}

	@Override
	public void saveOrUpdate(Object entity) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().saveOrUpdate(entity);
	}

	@Override
	public void update(Object entity) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(entity);
	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub
		this.deleteByEntity(this.get(id));
	}

	@Override
	public void deleteByEntity(Object entity) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().delete(entity);
	}

	/*
	 *
	 * 分页查询，通过hql和page对象查询并封转成分页对象返回
	 */
	@Override
	public Page getPageByHql(String hql, Page page) {
		// TODO Auto-generated method stub

		Page rePage = new Page();
		StringBuffer totalRowsHql = new StringBuffer("select count(*) ");
		totalRowsHql.append(hql);
		int totalRows = ((Long) this.getSession().createQuery(totalRowsHql.toString()).uniqueResult()).intValue();
		int totalPages = (int)(Math.ceil((double)totalRows/(double)page.getPageSize()));
		rePage.setTotalRows(totalRows);
		rePage.setTotalPages(totalPages);
		Query q = this.getSession().createQuery(hql.toString());
		int first = page.getPageSize()*(page.getPageNo()-1);
		int max = page.getPageSize();
		q.setFirstResult(first);
		q.setMaxResults(max);
		List list = q.list();
		rePage.setList(list);
		rePage.setPageNo(page.getPageNo());
		rePage.setPageSize(page.getPageSize());

		return rePage;
	}
}
